<?php

namespace app\queue\redis\shushu;

use app\extensions\lib\push\BasePush;
use app\extensions\lib\ta_shushu\Shushu;
use app\model\Package;
use app\model\TokenInfo;
use support\Db;
use support\Log;
use Webman\RedisQueue\Consumer;

class DeviceEvent implements Consumer
{
    // 要消费的队列名
    public $queue = 'queue_shushu_device_event_log';

    public $connection = 'default';


    protected function getShushu()
    {

    }


    // 消费
    public function consume($data)
    {
        $package_id = $data['package_id'];

        if(!$package_id){
            $udid = $data['udid'] ?? '';
            $TokenInfo = new TokenInfo();
            $data['package_id'] = $package_id = $TokenInfo->where('udid',$udid)->value('package_id');
        }
        $config = Package::getPackageConfig()[$package_id];
        $cate_id = $config['cate_id'] ?? 0;
        $game_id = $config['game_id'] ?? 0;
        if(!$cate_id || !$game_id){
            Log::channel('shushu')->error("ta::pushLog:no cate_id or game_id".json_encode($data));
        }
        $params = $data['params'];
        $params[3]  = array_merge(compact('cate_id','game_id'),$params[3]);//合并其他信息
        $event_id = $params[5] ?? '';
        $is_add = $params[6] ?? true;
        $Shushu = new Shushu($cate_id);

        if($event_id && $is_add===false){
            $start_date = date('Y-m-d', strtotime('-1 day'));
            $end_date = date('Y-m-d',strtotime($start_date)+86400*2);
            $event_name = BasePush::EVENT_DEVICE_PUSH_LOG;
            $condition = "\"#event_id\" = '$event_id' and \"#event_name\" = '$event_name'";
            $devicedata = $Shushu->getEventId($start_date,$end_date,$condition);
            if(empty($devicedata)){
                if(isset($data['retry_count'])){
                    $data['retry_count']++;
                }else{
                    $data['retry_count'] = 1;
                }
                if($data['retry_count']<100){
                    \Webman\RedisQueue\Redis::send($this->queue,$data,30);
                    return;
                }else{
                    Log::channel('shushu')->warning("RequestEvent_retry_error".json_encode($data));
                }


            }
        }


        $status = $Shushu->pushLog(...$params);
        Log::channel('shushu')->info("ta::pushLog:status:$status".json_encode($params));


    }
}
